﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace TaoWeb
{
    public static class EString
    {
        #region 数据转换

        #region 转Int
        public static int ToInt(this string t)
        {
            int n;
            if (!int.TryParse(t, out n))
                return 0;
            return n;
        }

        public static int ToInt(this string t, int pReturn)
        {
            int n;
            if (!int.TryParse(t, out n))
                return pReturn;
            return n;
        }

        public static bool IsInt(this string t)
        {
            int n;
            return int.TryParse(t, out n);
        }
        #endregion

        #region 转Int16

        public static Int16 ToInt16(this string t)
        {
            Int16 n;
            if (!Int16.TryParse(t, out n))
                return 0;
            return n;
        }


        public static Int16 ToInt16(this string t, Int16 pReturn)
        {
            Int16 n;
            if (!Int16.TryParse(t, out n))
                return pReturn;
            return n;
        }

        public static bool IsInt16(this string t)
        {
            Int16 n;
            return Int16.TryParse(t, out n);
        }
        #endregion

        #region 转byte

        public static byte Tobyte(this string t)
        {
            byte n;
            if (!byte.TryParse(t, out n))
                return 0;
            return n;
        }

        public static byte Tobyte(this string t, byte pReturn)
        {
            byte n;
            if (!byte.TryParse(t, out n))
                return pReturn;
            return n;
        }

        public static bool Isbyte(this string t)
        {
            byte n;
            return byte.TryParse(t, out n);
        }
        #endregion

        #region 转Long

        public static long ToLong(this string t)
        {

            long n;
            if (!long.TryParse(t, out n))
                return 0;
            return n;
        }

        public static long ToLong(this string t, long pReturn)
        {
            long n;
            if (!long.TryParse(t, out n))
                return pReturn;
            return n;
        }

        public static bool IsLong(this string t)
        {
            long n;
            return long.TryParse(t, out n);
        }
        #endregion

        #region 转Double
        /// <summary>
        /// 转Int,失败返回0
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public static double ToDouble(this string t)
        {
            double n;
            if (!double.TryParse(t, out n))
                return 0;
            return n;
        }

        /// <summary>
        /// 转Double,失败返回pReturn
        /// </summary>
        /// <param name="e"></param>
        /// <param name="pReturn">失败返回的值</param>
        /// <returns></returns>
        public static double ToDouble(this string t, double pReturn)
        {
            double n;
            if (!double.TryParse(t, out n))
                return pReturn;
            return n;
        }

        /// <summary>
        /// 是否是Double true:是 false:否
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public static bool IsDouble(this string t)
        {
            double n;
            return double.TryParse(t, out n);
        }
        #endregion

        #region 转Decimal

        public static decimal ToDecimal(this string t)
        {
            decimal n;
            if (!decimal.TryParse(t, out n))
                return 0;
            return n;
        }


        public static decimal ToDecimal(this string t, decimal pReturn)
        {
            decimal n;
            if (!decimal.TryParse(t, out n))
                return pReturn;
            return n;
        }

        public static bool IsDecimal(this string t)
        {
            decimal n;
            return decimal.TryParse(t, out n);
        }
        #endregion

        #region 转DateTime

        public static DateTime ToDateTime(this string t)
        {
            DateTime n;
            if (!DateTime.TryParse(t, out n))
                return DateTime.Now;
            return n;
        }

        public static DateTime ToDateTime(this string t, DateTime pReturn)
        {
            DateTime n;
            if (!DateTime.TryParse(t, out n))
                return pReturn;
            return n;
        }


        public static string ToDateTime(this string t, string pFormat, string pReturn)
        {
            DateTime n;
            if (!DateTime.TryParse(t, out n))
                return pReturn;
            return n.ToString(pFormat);
        }


        public static string ToDateTime(this string t, string pFormat)
        {
            return t.ToDateTime(pFormat, string.Empty);
        }

        public static string ToShortDateTime(this string t)
        {
            return t.ToDateTime("yyyy-MM-dd", string.Empty);
        }

        public static bool IsDateTime(this string t)
        {
            DateTime n;
            return DateTime.TryParse(t, out n);
        }
        #endregion

        #region 与int[]相关

        public static int[] ToIntArr(this string t)
        {
            return t.ToIntArr(new char[] { ',' });
        }


        public static int[] ToIntArr(this string t, char[] pSplit)
        {
            if (t.Length == 0)
            {
                return new int[] { };
            }

            string[] ArrStr = t.Split(pSplit, StringSplitOptions.None);
            int[] iStr = new int[ArrStr.Length];

            for (int i = 0; i < ArrStr.Length; i++)
                iStr[i] = int.Parse(ArrStr[i]);

            return iStr;
        }


        #endregion

        #region 过滤字符串的非int,重新组合成字符串

        public static string ClearNoInt(this string t, char pSplit)
        {
            string sStr = string.Empty;
            string[] ArrStr = t.Split(pSplit);

            for (int i = 0; i < ArrStr.Length; i++)
            {
                string lsStr = ArrStr[i];

                if (lsStr.IsInt())
                    sStr += lsStr + pSplit;
                else
                    continue;
            }

            if (sStr.Length > 0)
                sStr = sStr.TrimEnd(pSplit);

            return sStr;
        }


        public static string ClearNoInt(this string t)
        {
            return t.ClearNoInt(',');
        }
        #endregion

        #region 是否可以转换成int[]

        public static bool IsIntArr(this string t, char pSplit)
        {
            string[] ArrStr = t.Split(pSplit);
            bool b = true;

            for (int i = 0; i < ArrStr.Length; i++)
            {
                if (!ArrStr[i].IsInt())
                {
                    b = false;
                    break;
                }
            }

            return b;
        }


        public static bool IsIntArr(this string t)
        {
            return t.IsIntArr(',');
        }
        #endregion

        #endregion

        #region 载取左字符
        /// <summary>
        /// 载取左字符
        /// </summary>
        /// <param name="t"></param>
        /// <param name="pLen">字符个数</param>
        /// <param name="pReturn">超出时后边要加的返回的内容</param>
        /// <returns></returns>
        public static string Left(this string t, int pLen, string pReturn)
        {
            if (t == null || t.Length == 0)
                return string.Empty;
            pLen *= 2;
            int i = 0, j = 0;
            foreach (char c in t)
            {
                if (c > 127)
                {
                    i += 2;
                }
                else
                {
                    i++;
                }

                if (i > pLen)
                {
                    return t.Substring(0, j) + pReturn;
                }

                j++;
            }

            return t;
        }

        public static string Left(this string t, int pLen)
        {
            return Left(t, pLen, string.Empty);
        }

        public static string StrLeft(this string t, int pLen)
        {
            if (t == null)
            {
                return "";
            }
            if (t.Length > pLen)
            {
                return t.Substring(0, pLen);
            }
            return t;
        }
        #endregion

        #region 删除文件名或路径的特殊字符

        private class ClearPathUnsafeList
        {
            public static readonly string[] unSafeStr = { "/", "\\", ":", "*", "?", "\"", "<", ">", "|" };
        }

        public static string ClearPathUnsafe(this string t)
        {
            foreach (string s in ClearPathUnsafeList.unSafeStr)
            {
                t = t.Replace(s, "");
            }

            return t;
        }
        #endregion

        #region 字符串真实长度 如:一个汉字为两个字节

        public static int LengthReal(this string s)
        {
            return Encoding.Default.GetBytes(s).Length;
        }
        #endregion

        #region 去除小数位最后为0的

        public static decimal ClearDecimal0(this string t)
        {
            decimal d;
            if (decimal.TryParse(t, out d))
            {
                return decimal.Parse(double.Parse(d.ToString("g")).ToString());
            }
            return 0;
        }
        #endregion

        #region 进制转换
        /// <summary>
        /// 16进制转二进制
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string Change16To2(this string t)
        {
            String BinOne = string.Empty;
            String BinAll = string.Empty;
            char[] nums = t.ToCharArray();
            for (int i = 0; i < nums.Length; i++)
            {
                string number = nums[i].ToString();
                int num = Int32.Parse(number, System.Globalization.NumberStyles.HexNumber);

                BinOne = Convert.ToString(num, 2).PadLeft(4, '0');
                BinAll = BinAll + BinOne;
            }
            return BinAll;
        }

        /// <summary>
        /// 二进制转十进制
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public static Int64 Change2To10(this string t)
        {
            char[] arrc = t.ToCharArray();
            Int64 all = 0, indexC = 1;
            for (int i = arrc.Length - 1; i >= 0; i--)
            {
                if (arrc[i] == '1')
                {
                    all += indexC;
                }
                indexC = indexC * 2;
            }

            return all;
        }


        public static byte[] Change2ToBytes(this string t)
        {
            List<byte> list = new List<byte>();

            char[] arrc = t.ToCharArray();
            byte n = 0;
            char c;
            int j = 0;
            //倒序获取位
            for (int i = arrc.Length - 1; i >= 0; i--)
            {
                c = arrc[i];

                if (c == '1')
                {
                    n += Convert.ToByte(Math.Pow(2, j));
                }
                j++;

                if (j % 8 == 0)
                {
                    list.Add(n);
                    j = 0;
                    n = 0;
                }
            }

            //剩余最高位
            if (n > 0)
                list.Add(n);

            byte[] arrb = new byte[list.Count];

            int j1 = 0;
            //倒序
            for (int i = list.Count - 1; i >= 0; i--)
            {
                arrb[j1] = list[i];
                j1++;
            }
            return arrb;
        }

        /// <summary>
        /// 二进制转化为索引id数据,从右到左
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public static int[] Change2ToIndex(this string t)
        {
            List<int> list = new List<int>();
            char[] arrc = t.ToCharArray();
            char c;
            int j = 0;

            for (int i = arrc.Length - 1; i >= 0; i--)
            {
                j++;
                c = arrc[i];

                if (c == '1')
                {
                    list.Add(j);
                }
            }

            return list.ToArray();
        }
        #endregion

        #region

        public static string HtmlEncode(this string t)
        {
            return HttpContext.Current.Server.HtmlEncode(t);
        }


        public static string HtmlDecode(this string t)
        {
            return HttpContext.Current.Server.HtmlDecode(t);
        }

        public static string URLEncode(this string t)
        {
            return HttpContext.Current.Server.UrlEncode(t);
        }

        public static string URLDecode(this string t)
        {
            return HttpContext.Current.Server.UrlDecode(t);
        }
        #endregion

        #region 向客户端输出内容

        public static void Write(this string t)
        {
            HttpContext.Current.Response.Write(t);
        }


        public static void WriteLine(this string t)
        {
            HttpContext.Current.Response.Write(t + "<br />");
        }

        public static string GetStringIfNotNull(this IDataReader dr, int i)
        {
            return dr.IsDBNull(i) ? string.Empty : dr.GetString(i);
        }
        public static double GetDoubleIfNotNull(this IDataReader dr, int i)
        {
            return dr.IsDBNull(i) ? 0.0 : dr.GetDouble(i);
        }
        public static int GetIntIfNotNull(this IDataReader dr, int i)
        {
            return dr.IsDBNull(i) ? 0 : dr.GetInt32(i);
        }
        public static DateTime GetDateIfNotNull(this IDataReader dr, int i)
        {
            return dr.IsDBNull(i) ? DateTime.MinValue : dr.GetDateTime(i);

        }
        public static bool IsNullOrEmpty(this string s)
        {
            return string.IsNullOrEmpty(s);
        }

        public static TValue GetValue<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue defaultValue = default(TValue))
        {
            return dict.ContainsKey(key) ? dict[key] : defaultValue;
        }

        public static Dictionary<TKey, TValue> TryAdd<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value)
        {
            if (dict.ContainsKey(key) == false) dict.Add(key, value);
            return dict;
        }
        /// <summary>
        /// 将键和值添加或替换到字典中：如果不存在，则添加；存在，则替换
        /// </summary>
        public static Dictionary<TKey, TValue> AddOrReplace<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value)
        {
            dict[key] = value;
            return dict;  
        }

        public static T GetEnum<T>(this IDataReader dr, int i)
        {
            return (T)Enum.Parse(typeof(T), dr.GetString(i), true);
        }

        public static string GetStringIfNotNull<T>(this object obj, string str)
        {
            if (obj == null)
                return null;
            else
            {
                return str;
            }
        }

        public static string ListToInClause(this IList<string> lst)
        {
            //Check parameter
            if (lst == null || lst.Count == 0)
                return "''";

            StringBuilder sb = new StringBuilder();
            foreach (string strT in lst)
                sb.Append(", '" + strT + "' ");

            return sb.Remove(0, 1).ToString();
        }
        public static string ListToInClause(this IList<int> lst)
        {
            //Check parameter
            if (lst == null || lst.Count == 0)
                return "''";

            StringBuilder sb = new StringBuilder();
            foreach (int strT in lst)
                sb.Append(", '" + strT + "' ");

            return sb.Remove(0, 1).ToString();
        }
        public static string ListToInClause<T>(this IList<T> lst)
        {
            //Check parameter
            if (lst == null || lst.Count == 0)
                return "''";

            StringBuilder sb = new StringBuilder();
            foreach (var strT in lst)
                sb.Append(", '" + strT + "' ");

            return sb.Remove(0, 1).ToString();
        }
        public static IList<int> StringSplitToIListInt(this string str)
        {
            IList<int> lst = new List<int>();
            if (str.IsNullOrEmpty())
            {
                return lst;
            }
            else
            {
                string[] s = str.Split(new string[] { DataFormatter.DataSeparator }, StringSplitOptions.None);
                
                foreach (var item in s)
                {
                    try
                    {
                        if(!item.IsNullOrEmpty())
                        lst.Add(item.ToInt());
                    }
                    catch (Exception ex)
                    {

                    }
                }
            }
            return lst;
        }

        public static IList<int> StringSplitToIListIntForView(this string str)
        {
            IList<int> lst = new List<int>();
            if (str.IsNullOrEmpty())
            {
                return lst;
            }
            else
            {
                string[] s = str.Split(new string[] { "$%" }, StringSplitOptions.None);

                foreach (var item in s)
                {
                    try
                    {
                        if (!item.IsNullOrEmpty())
                            lst.Add(item.ToInt());
                    }
                    catch (Exception ex)
                    {

                    }
                }
            }
            return lst;
        }
        public static List<string> StringSplitToIList(this string str)
        {
            List<string> lst = new List<string>();
            if (str.IsNullOrEmpty())
            {
                return lst;
            }
            else
            {
                string[] s = str.Split(new string[] { DataFormatter.DataSeparator }, StringSplitOptions.None);

                foreach (var item in s)
                {
                        if (!item.IsNullOrEmpty())
                            lst.Add(item);
                }
            }
            return lst;
        }
        #endregion

    }
}
